package cn.czh.controller;

import cn.czh.domain.Middle;
import cn.czh.domain.Movie;
import cn.czh.domain.User;
import cn.czh.feign.MovieFeignClient;
import cn.czh.service.IUserService;
import cn.czh.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private MovieFeignClient movieFeignClient;

    @Autowired
    private IUserService userService;

    /**
     * 查询所有电影
     *
     * @return
     */
    @GetMapping("/user/findAll")
    public List<Movie> findAll() {
        return movieFeignClient.findAll();
    }


    /**
     * 查询单个电影
     *
     * @param id
     * @return
     */
    @GetMapping("/user/getByMovieId/{id}")
    public Movie getByMovieId(@PathVariable("id") Long id) {
        return movieFeignClient.getById(id);
    }


    /**
     * 查询单个用户
     *
     * @param id
     * @return
     */
    @GetMapping("/user/getById/{id}")
    public User getById(@PathVariable("id") Long id) {
        return userService.getById(id);
    }


    /**
     * 购买电影票
     *
     * @param middle
     * @return
     */
    @PostMapping("/user/buy")
    public AjaxResult buyTicket(@RequestBody Middle middle) {
        try {
            userService.buy(middle);
            return new AjaxResult();
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "操作失败");
        }
    }


    /**
     * 新增或修改用户
     *
     * @param user
     * @return
     */
    @PostMapping("/user/addOrUpdate")
    public AjaxResult addOrUpdateUser(@RequestBody User user) {
        try {
            if (user.getId() == null) { //如果用户Id为null
                userService.addUser(user);
            } else {
                userService.updateUser(user);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "操作失败");
        }
    }

    /**
     * 观看电影
     * @param middle
     * @return
     */
    @PostMapping("/user/see")
    public AjaxResult seeMovie(@RequestBody Middle middle) {
        try {
            userService.seeMovie(middle);
            return new AjaxResult();
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "操作失败");
        }
    }
}


